/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ScrollView,
  RefreshControl,
  AsyncStorage,
  TouchableOpacity,
  Dimensions,
  Alert
} from 'react-native';
 
import Grid from 'react-native-grid-component';
import CacheableImage from 'react-native-cacheable-image'
import styles1 from './styles/Pager.style';
import { colors } from './styles/Pager.style';

var Header = require("./Component/Header");
var _navigator;

var net = require("./net/NetUitl");
var user_id;

class MoreArticle extends Component {
	constructor(props) {  
		super(props);
		
		_navigator = this.props.navigator;
		this.state = {dataSource: [],isRefreshing:false,};
  	}
	
	componentDidMount() {
//		net.postJson("http://api.idolly.com/m/articleapi/find"
//			,null
//			,this._netCallBack.bind(this)
//			,this._errorCallBack);
		_this = this;

		this.requireUrl = this.requireUrl.bind(this);
		this._pressBtn = this._pressBtn.bind(this);
		this._renderItem = this._renderItem.bind(this);
		this._netCallBack = this._netCallBack.bind(this);
		this._errorCallBack = this._errorCallBack.bind(this);
		this._onRefresh = this._onRefresh.bind(this);
		
		AsyncStorage.getItem("user_id",function(errors,result){
			
			if(result != null){
				user_id = result;
				_this.requireUrl();
			}
		});
	}
	
	async requireUrl(){
		let formData = new FormData();  
		formData.append("sort",this.props.sort);  
		var fetchOptions = {
			method: 'POST',
			headers: { 
			    'Accept': 'application/json',
			},
			body: formData
		}; 
		        
		net.postFrom("http://www.idolly.com/article/index/articleBySort"
			,fetchOptions
			,this._netCallBack
			,this._errorCallBack);
	}
	
	_errorCallBack(data){
		_this = this;
      	
      	AsyncStorage.getItem('more'+this.props.sort,function(errors,result){
			var json = eval('(' + result + ')');
			if(result != null){
				_this._netCallBack(json);
			}
			
		});
	}
	
	async _netCallBack(data){
		this.setState({dataSource: data.fullinfo,});
				
		AsyncStorage.setItem('more'+this.props.sort,JSON.stringify(data),function(errs){
            //TODO:错误处理
            if (errs) {
                console.log('存储错误');
            }
            if (!errs) {
                console.log('存储无误');
            }
        });
//		
//		this.setState({activitydataSource: findlist});
//		
//		this.setState({healthyinfodataSource: data.healthyinfodataSource});
	}
	
	_pressBtn(userid){
		var url = "http://www.idolly.com/article/index/articledetail?id="+userid;
		_navigator.push({id:"Web",url:url,articleid:userid});
	}
	
	_renderItem(data, i){
		console.log(data);
		return(
			<TouchableOpacity key={i} onPress={()=>this._pressBtn(data.id)}>
        		<View style={styles.item}>
				    <View style={styles.child}>
				    	<CacheableImage 
					        resizeMode="cover"
					        style={{height:Dimensions.get('window').width/2,width:Dimensions.get('window').width}}
					        source={{uri: data.image}}
					    />
				    </View>
			    </View>
		    </TouchableOpacity>
		);
	}
	
	_onRefresh(){
		this.setState({isRefreshing:true});
		
		let formData = new FormData();  
		formData.append("sort",this.props.sort);  
		var fetchOptions = {
			method: 'POST',
			headers: { 
			    'Accept': 'application/json',
			},
			body: formData
		}; 
		
		net.postJson("http://www.idolly.com/article/index/articleBySort"
			,fetchOptions
			,this._netCallBack
			,this._errorCallBack);
		setTimeout(() => {
	      	this.setState({isRefreshing:false});
	    }, 1000);
	}
	
	render() {
	    return (
	      	<View style={styles1.container}>
	      		<Header name={this.props.title} IconLeft="chevron-left" onPressLeft={()=>_navigator.pop()}/>
	      		<ScrollView style={styles.scrollview}
					refreshControl={
				        <RefreshControl
				            refreshing={this.state.isRefreshing}
				            onRefresh={this._onRefresh}
				            tintColor="#ff0000"
				            title="Loading..."
				            titleColor="#00ff00"
				            colors={['#ff0000', '#00ff00', '#0000ff']}
				            progressBackgroundColor="#ffff00"
				        />
			        }> 
			        <View style={styles1.pager}>
				        <View style={{height:5}}>
				        </View>
				       	<Grid
					        style={styles.item}
					        renderItem={this._renderItem}
					        data={this.state.dataSource}
					        itemsPerRow={1}
					    />
			        </View>
				</ScrollView>
	      	</View>
	    );
	}
}

const styles = StyleSheet.create({
	container: {
	    flex: 1,
	    justifyContent: 'center',
	    alignItems: 'center',
	    backgroundColor: '#F5FCFF',
	},
	scrollview: {  
	    flex: 1,  
	   	width:Dimensions.get('window').width,
	},
	item:{
		width:Dimensions.get('window').width,
		height:140,
		margin:10
	},
});

module.exports = MoreArticle;
